using Refresh;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace Light
{
    public class ItemInSlotInfo : RefreshData<ItemInSlotInfo>
    {
        public AbstractItemSO item;
    }

    public class ItemInSlot : MonoBehaviour, IRefresh, IBeginDragHandler, IEndDragHandler, IDragHandler
    {
        private CanvasGroup canvasGroup;

        private Transform originParent;
        private QuickSlotBarController parentPanel;

        private Vector2 sizeData;

        private void Awake()
        {
            //��ȡ��Ӧ������
            canvasGroup = GetComponent<CanvasGroup>();
        }

        public void OnBeginDrag(PointerEventData eventData)
        {
            originParent = transform.parent;

            transform.SetParent(transform.parent.parent.parent);
            transform.position = eventData.position;
            canvasGroup.blocksRaycasts = false; //���߿��Դ�͸
        }

        public void OnDrag(PointerEventData eventData)
        {
            transform.position = eventData.position;
            Debug.Log("-----���ߵ�ǰ��⵽�Ķ���" + eventData.pointerCurrentRaycast.gameObject.name);
        }

        public void OnEndDrag(PointerEventData eventData)
        {
            //����Item��Slot
            if (eventData.pointerCurrentRaycast.gameObject.name.EndsWith("Slot"))
            {
                parentPanel.SwitchItemIndex(gameObject, eventData.pointerCurrentRaycast.gameObject); //���ݲ���Ľ���

                //UI�����ϵĽ���
                var trans = eventData.pointerCurrentRaycast.gameObject.transform;
                transform.SetParent(trans.parent);
                transform.position = trans.position;
                trans.SetParent(originParent);
                trans.position = originParent.position;
            }

            //�յ�Slot
            else if (eventData.pointerCurrentRaycast.gameObject.name.StartsWith("Slot"))
            {
                parentPanel.SwitchItemIndex(gameObject, null, eventData.pointerCurrentRaycast.gameObject); //���ݲ���Ľ���


                var trans = eventData.pointerCurrentRaycast.gameObject.transform;
                transform.SetParent(trans);
                transform.position = trans.position;
            }
            else
            {
                Debug.Log("----û���ƶ������ʵ�λ�ã��ع�ԭλ");
                transform.SetParent(originParent);
                transform.position = originParent.position;
            }

            canvasGroup.blocksRaycasts = true;
        }

        public void Refresh<T>(T data) where T : RefreshData<T>, new()
        {
            var info = data as ItemInSlotInfo;
            GetComponent<Image>().sprite = info.item.image;
        }

        public void Init(QuickSlotBarController parentPanel)
        {
            this.parentPanel = parentPanel;
        }
    }
}